import random
from datetime import datetime
from django.shortcuts import render, HttpResponse
from django import forms
from manage_worker import models
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from manage_worker.utills.bootsrtap import BootStrapModelForm
from manage_worker.utills.pagination import Pagination


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        fields = '__all__'
        widgets = {
            'title': forms.TextInput
        }
        exclude = ['oid', 'admin']


def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    form = OrderModelForm()
    page_object = Pagination(request, queryset=queryset)
    context = {
        'form': form,
        'queryset': page_object.page_queryset,  # 分完页的数据
        'page_string': page_object.html()  # 页码
    }
    return render(request, 'order_list.html', context)


@csrf_exempt
def order_save(request):
    print(request.POST)
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 生成订单号
        form.instance.oid = datetime.now().strftime('%Y%m%d%H%M%S') + str(random.randint(1000, 9999))
        # 获取session中存的用户id，登录的是谁的账号，获取出来就是谁的
        form.instance.admin_id = request.session['info']['id']
        form.save()
        data_list = {'status': True, 'data': [11, 22, 34, 55]}

        return JsonResponse(data_list)
    data_list = {'status': False, 'error': form.errors}
    return JsonResponse(data_list)


def order_delete(request):
    id = request.GET.get('id')
    exists = models.Order.objects.filter(id=id).exists()
    if not exists:
        return JsonResponse({'status': False, 'error': '数据不存在'})
    models.Order.objects.filter(id=id).delete()
    return JsonResponse({'status': True})


def order_detail(request):
    id = request.GET.get('id')
    row_obj = models.Order.objects.filter(id=id).values('title', 'price', 'status').first()
    if not row_obj:
        return JsonResponse({'status': False, 'error': '数据不存在'})
    result = {
        'status': True,
        'data': row_obj
    }
    return JsonResponse(result)


@csrf_exempt
def order_edit(request):
    id = request.GET.get('id')
    row_obj = models.Order.objects.filter(id=id).first()
    if not row_obj:
        return JsonResponse({'status': False, 'tips': '数据不存在,请刷新页面重试'})
    form = OrderModelForm(data=request.POST, instance=row_obj)
    if form.is_valid():
        form.save()
        return JsonResponse({'status': True})
    data_list = {'status': False, 'error': form.errors}
    return JsonResponse(data_list)
